package org.whatever.aha.zjut.platform.controller.judge;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.whatever.aha.zjut.base.constant.AuthConst;
import org.whatever.aha.zjut.base.constant.ErrorCode;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.base.dto.AjaxResult;
import org.whatever.aha.zjut.base.exception.AppException;
import org.whatever.aha.zjut.platform.annotation.StageLimit;
import org.whatever.aha.zjut.platform.dto.school.ProjectScoreDto;
import org.whatever.aha.zjut.platform.entity.project.Project;
import org.whatever.aha.zjut.platform.entity.school.JudgeProjectDistribution;
import org.whatever.aha.zjut.platform.entity.school.ProjectScore;
import org.whatever.aha.zjut.platform.service.UserService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageAwardService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionStageService;
import org.whatever.aha.zjut.platform.service.judge.JudgeService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;
import org.whatever.aha.zjut.platform.service.school.JudgeProjectDistributionService;
import org.whatever.aha.zjut.platform.service.school.ProjectScoreService;
import org.whatever.aha.zjut.platform.vo.PageVo;
import org.whatever.aha.zjut.platform.vo.competition.CompetitionRoughVo;
import org.whatever.aha.zjut.platform.vo.competition.CompetitionStageRoughInfoVo;
import org.whatever.aha.zjut.platform.vo.competition.CompetitionStageVo;
import org.whatever.aha.zjut.platform.vo.judge.JudgeProjectRoughInfoVo;
import org.whatever.aha.zjut.platform.vo.judge.StandardAndAwardInfoVo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Vc
 * @version 1.0
 * @Desc
 * @date 2021/11/26 1:07
 */
@Api(tags = "评委相关操作")
@RequestMapping("/v1/judge")
@RequiredArgsConstructor
@RestController
@Validated
@SaCheckRole(value = {AuthConst.R_judge})
public class judgeController {
    final JudgeService judgeService;
    final CompetitionStageService competitionStageService;
    final ProjectScoreService projectScoreService;
    final ProjectService projectService;
    final UserService userService;

    /**
     * 获取登录评委要审核的竞赛信息
     *
     * @return
     */
    @GetMapping("/getJudgingCompInfo")
    public AjaxResult<Map> getJudgingCompInfo(){
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(judgeService.getJudgingCompInfo(userId));
    }

    /**
     * 获取竞赛标准和获奖信息
     *
     * @param compId
     * @param stageId
     */
    @GetMapping("/getJudgeStandardAndAwardInfo/{compId}/{stageId}")
    public AjaxResult<StandardAndAwardInfoVo> getJudgeStandardAndAwardInfo(@PathVariable("compId") int compId,@PathVariable("stageId") int stageId){
        return AjaxResult.SUCCESS(judgeService.getJudgeStandardAndAwardInfo(compId, stageId));
    }

    /**
     * 根据阶段Id和组名分页获取项目粗略信息
     *
     * @param stageId
     * @param groupName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getProjectRoughPageableByGroup/{stageId}")
    public AjaxResult<PageVo<List<JudgeProjectRoughInfoVo>>> getProjectRoughPageableByGroupExceptProvinceRec(@PathVariable("stageId") int stageId,
                                                                                            @RequestParam(value = "groupName") String groupName,
                                                                                            @RequestParam(value = "pageNum") int pageNum,
                                                                                            @RequestParam(value = "pageSize") int pageSize){
        //没有此组名则返回空分页  报警项目不存在
        if(projectService.getProjectsByStageId(stageId).stream().filter(project -> groupName.equals(project.getProjectGroup())).collect(Collectors.toList()).isEmpty()){
            return AjaxResult.SUCCESS(new PageVo<>());
        }
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(projectService.getProjectRoughPageableByGroupExceptProvinceRec(stageId, groupName, pageNum, pageSize, userId));
    }


    /**
     * 评委进行打分  已经评了的不能评  评审在评审阶段进行评分  已经提交公示结果了不能改  省级直推项目评委不可以操作
     *
     * @param projectScoreDto
     * @return
     */
    @StageLimit({"judge"})
    @ApiOperation("评委打分操作")
    @PostMapping("/addProjectScore")
    public AjaxResult<Integer> addProjectScore(@RequestParam(value = "stageId") int stageId,@RequestBody ProjectScoreDto projectScoreDto){
        int userId = StpUtil.getLoginIdAsInt();
        CompetitionStageVo stageVoById = competitionStageService.getStageVoById(projectScoreDto.getStageId());
        if(stageVoById.getStageStatus() == StatusConstant.COMPETITION_STAGE_STATUS_COMPLETED.getCode()){
            throw new AppException(ErrorCode.ILLEGAL_UPDATE_COMPELETED_COMPETITION);
        }
        Project project = projectService.getProjectById(projectScoreDto.getProjectId());
        if(project.getProjectProvinceRec()){
            throw new AppException(ErrorCode.JUDGE_CANNOT_JUDGE_PROVINCE_REC_PROJECT);
        }
        ProjectScore projectScoreByStageId = projectScoreService.getProjectScoreByJudgeIdAndProjectId(projectScoreDto.getStageId(), userId, projectScoreDto.getProjectId());
        if(projectScoreByStageId != null){
            throw new AppException(ErrorCode.JUDGE_ALREADY_COMMENT);
        }
        projectScoreDto.setJudgeId(userId);
        projectScoreDto.setJudgeName(userService.getUserRoughInfoById(userId).getUserName());
        judgeService.addProjectScore(projectScoreDto);
        //若校级管理员已更改总分则不更新项目均分，否则更新均分
        if(project.getProjectScore() == null){
            project.setProjectAvgScore(projectScoreService.getJudgeAvgScore(projectScoreDto.getProjectId()));
            projectService.updateProject(project);
        }
        return AjaxResult.SUCCESS(project.getProjectId());
    }

    /**
     * 评委修改打分评论  非上次已评分的不能修改  评审在评审阶段进行评分  已经提交公示结果了不能改  省级直推项目评委不可以操作
     *
     * @param projectScoreDto
     * @return
     */
    @StageLimit({"judge"})
    @PutMapping("/modifyProjectScore")
    public AjaxResult<Integer> modifyProjectScore(@RequestParam(value = "stageId") int stageId,@RequestBody ProjectScoreDto projectScoreDto){
        int userId = StpUtil.getLoginIdAsInt();
        CompetitionStageVo stageVoById = competitionStageService.getStageVoById(projectScoreDto.getStageId());
        if(stageVoById.getStageStatus() == StatusConstant.COMPETITION_STAGE_STATUS_COMPLETED.getCode()){
            throw  new AppException(ErrorCode.ILLEGAL_UPDATE_COMPELETED_COMPETITION);
        }
        ProjectScore projectScoreByStageId = projectScoreService.getProjectScoreByJudgeIdAndProjectId(projectScoreDto.getStageId(), userId, projectScoreDto.getProjectId());
        if(projectScoreByStageId == null){
            throw new AppException(ErrorCode.JUDGE_NOT_COMMENT_TO_MODIFY);
        }
        if(projectService.getProjectById(projectScoreDto.getProjectId()).getProjectProvinceRec()){
            throw new AppException(ErrorCode.JUDGE_CANNOT_JUDGE_PROVINCE_REC_PROJECT);
        }
        projectScoreDto.setJudgeId(userId);
        projectScoreDto.setJudgeName(userService.getUserRoughInfoById(userId).getUserName());
        judgeService.modifyProjectScore(projectScoreDto);
        //若校级管理员已更改总分则不更新项目均分，否则更新均分
        Project project = projectService.getProjectById(projectScoreDto.getProjectId());
        if(project.getProjectScore() == null){
            project.setProjectAvgScore(projectScoreService.getJudgeAvgScore(projectScoreDto.getProjectId()));
            projectService.updateProject(project);
        }
        return AjaxResult.SUCCESS(project.getProjectId());
    }


    /**
     * 获取完成进度
     *
     * @param stageId
     * @param groupName
     * @return
     */
    @GetMapping("/getAlreadyJudgedProjectNum/{stageId}")
    public AjaxResult<Integer> getAlreadyJudgedProjectNum(@PathVariable("stageId") int stageId,
                                                          @RequestParam(value = "groupName") String groupName){
        //没有此组名则报警项目不存在
        if(projectService.getProjectsByStageId(stageId).stream().filter(project -> groupName.equals(project.getProjectGroup())).collect(Collectors.toList()).isEmpty()){
//            throw new AppException(ErrorCode.PROJECT_NOT_EXIST);
//            return AjaxResult.FAIL(null);
            return AjaxResult.SUCCESS(null);
        }
        int userId = StpUtil.getLoginIdAsInt();
        return AjaxResult.SUCCESS(projectScoreService.getAlreadyJudgedProjectNum(stageId, groupName, userId));
    }

    /**
     * 根据项目Id获取评委打分和评论
     *
     * @param projectId
     * @return
     */
    @GetMapping("/getScoreAndComment/{stageId}/{projectId}")
    public AjaxResult<Map> getAlreadyJudgedProjectNum(@PathVariable("stageId") int stageId,
                                                          @PathVariable("projectId") int projectId){
        int userId = StpUtil.getLoginIdAsInt();
        ProjectScore projectScore = projectScoreService.getProjectScoreByJudgeIdAndProjectId(stageId, userId, projectId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("score", projectScore == null ? null : projectScore.getScore());
        map.put("comment", projectScore == null ? null : projectScore.getJudgeComment());
        return AjaxResult.SUCCESS(map);
    }


}
